package com.fy56.platform.logistics.websocket;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by lilianqiang on 2015-08-21.
 */
public class CrossServlet extends WebSocketServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.addHeader("Access-Control-Allow-Origin","*");
        response.addHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
        response.addHeader("Access-Control-Max-Age", "50");
        response.addHeader("Access-Control-Allow-Headers", "X-Requested-With,X_Requested_With");
        this.doPost(request, response);

    }

    @Override
    protected StreamInbound createWebSocketInbound(String s, HttpServletRequest httpServletRequest) {
        return null;
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.addHeader("Access-Control-Allow-Origin","*");
        response.addHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
        response.addHeader("Access-Control-Max-Age", "50");
        response.addHeader("Access-Control-Allow-Headers", "X-Requested-With,X_Requested_With");

        HttpSession session = request.getSession();
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("sessionId",session.getId());
        String result = request.getParameter("callback") + "(" + JSON.toJSONString(jsonObject) + ")";

        response.setContentType("text/javascript");
        response.getWriter().print(result);
    }
}
